from django.db import models
from django.contrib.auth import get_user_model
from django.conf import settings

User = get_user_model()


class AIAssistant(models.Model):
    """AI助手模型"""
    name = models.CharField(max_length=50, verbose_name="助手名称")
    description = models.TextField(verbose_name="助手描述")
    avatar = models.ImageField(upload_to='assistants/', null=True, blank=True, verbose_name="助手头像")
    personality = models.CharField(
        max_length=20,
        verbose_name="性格特征",
        choices=[
            ('professional', '专业型'),
            ('friendly', '友好型'),
            ('efficient', '高效型'),
            ('analytical', '分析型'),
            ('creative', '创造型')
        ]
    )
    learning_style = models.CharField(
        max_length=20,
        verbose_name="学习风格",
        choices=[
            ('visual', '视觉型'),
            ('auditory', '听觉型'),
            ('kinesthetic', '动手型'),
            ('reading', '阅读型'),
            ('multimodal', '多模态')
        ],
        default='multimodal'
    )
    specialization = models.CharField(
        max_length=20,
        verbose_name="专精领域",
        choices=[
            ('exam_prep', '考试准备'),
            ('note_taking', '笔记整理'),
            ('time_management', '时间管理'),
            ('research', '研究辅助'),
            ('general', '通用')
        ],
        default='general'
    )
    expertise = models.JSONField(verbose_name="专业领域", default=list)
    prompt_template = models.TextField(verbose_name="提示词模板")
    is_active = models.BooleanField(default=True, verbose_name="是否启用")
    interaction_count = models.IntegerField(default=0, verbose_name="互动次数")
    average_rating = models.FloatField(default=0.0, verbose_name="平均评分")
    created_by = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        related_name='created_assistants',
        verbose_name="创建者"
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        db_table = 'ai_assistant_profile'
        ordering = ['-created_at']
        verbose_name = 'AI助手'
        verbose_name_plural = 'AI助手'

    def __str__(self):
        return f"{self.name} ({self.get_personality_display()})"

    def update_rating(self, new_rating: int):
        """更新助手评分"""
        self.interaction_count += 1
        self.average_rating = (self.average_rating * (self.interaction_count - 1) + new_rating) / self.interaction_count
        self.save()


class AssistantInteraction(models.Model):
    """助手交互记录"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="用户")
    assistant = models.ForeignKey(AIAssistant, on_delete=models.CASCADE, verbose_name="AI助手")
    interaction_type = models.CharField(
        max_length=50,
        verbose_name="交互类型",
        choices=[
            ('note_summary', '笔记总结'),
            ('task_planning', '任务规划'),
            ('study_advice', '学习建议'),
            ('time_management', '时间管理'),
            ('content_creation', '内容创作'),
            ('exam_preparation', '考试准备'),
            ('knowledge_quiz', '知识测验'),
            ('progress_tracking', '进度跟踪')
        ]
    )
    input_content = models.TextField(verbose_name="输入内容")
    output_content = models.TextField(verbose_name="输出内容")
    feedback_rating = models.IntegerField(null=True, verbose_name="反馈评分")
    feedback_comment = models.TextField(null=True, blank=True, verbose_name="反馈评论")
    duration = models.IntegerField(default=0, verbose_name="交互时长(秒)")
    token_count = models.IntegerField(default=0, verbose_name="Token数量")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        db_table = 'ai_assistant_interaction'
        ordering = ['-created_at']
        verbose_name = 'AI助手交互记录'
        verbose_name_plural = 'AI助手交互记录'

    def __str__(self):
        return f"{self.user.username} - {self.assistant.name} - {self.get_interaction_type_display()}"

    def save(self, *args, **kwargs):
        """重写保存方法,更新助手评分"""
        is_new = self.pk is None
        super().save(*args, **kwargs)

        if is_new and self.feedback_rating is not None:
            self.assistant.update_rating(self.feedback_rating)


class AIAnalysisHistory(models.Model):
    """AI分析历史记录"""
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    content_preview = models.TextField()
    analysis_result = models.JSONField()
    note_id = models.IntegerField(null=True, blank=True)
    content_hash = models.CharField(max_length=64)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['user', '-created_at']),
            models.Index(fields=['content_hash']),
        ]
